package Tree;

import java.util.ArrayList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-29  15:08
 * @Description: TODO
 * @Version: 1.0
 */
public class 二叉搜索树的众数501 {
    TreeNode pre;
    int count = 0;
    int maxCount = 0;
    ArrayList<Integer> list = new ArrayList<>();

    public int[] findMode(TreeNode root) {
        if (root == null) {
            return null;
        }
        //左
        findMode(root.left);
        // 中
        if (pre != null && pre.val != root.val) {
            count = 1;
        } else {
            count++;
        }
        pre = root;
        if (count == maxCount) {
            list.add(root.val);
        }
        if (count > maxCount) {
            maxCount = count;
            list.clear();
            list.add(root.val);
        }
        //右
        findMode(root.right);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
